package com.dmatek.uwb.xml.util.iassign;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Element;

import com.dmatek.uwb.util.tool.StringUtil;

/***
 * 属性匹配并赋值工具
 * @author zhangfu
 * @data 2019年6月14日 下午2:10:59
 * @Description
 *  
 */
public class CommonAssignTool extends BaseAssignTool {
	@Override
	public <T> void assign(String name, String val,Element element, T clazz,
			@SuppressWarnings("unchecked") Map<String, Object>... maps) throws IllegalArgumentException,
			IllegalAccessException {
		if(!isField(name, clazz.getClass())) {
			return;
		}
		Field field = getField(name, clazz.getClass());
		if(null != field) {
			field.setAccessible(true);
			String typeName = field.getGenericType().getTypeName();
			if("java.lang.String".equalsIgnoreCase(typeName)) {
				field.set(clazz, val);
			} else if("int".equalsIgnoreCase(typeName)) {
				field.set(clazz, Integer.parseInt(val));
			} else if("boolean".equalsIgnoreCase(typeName)) {
				field.set(clazz, Boolean.parseBoolean(val));
			} else if("float".equalsIgnoreCase(typeName)) {
				field.set(clazz, Float.parseFloat(val));
			} else if("double".equalsIgnoreCase(typeName)) {
				field.set(clazz, Double.parseDouble(val));
			} else if("long".equalsIgnoreCase(typeName)) {
				field.set(clazz, Long.parseLong(val));
			} else if("java.util.List<java.lang.String>".equalsIgnoreCase(typeName)){
				field.set(clazz, elementToList(element));
			}
			else { // 引用类型
				field.set(clazz, maps[0].get(val));
			}
		}
	}
	
	private List<String> elementToList(Element element) {
		List<String> elements = new ArrayList<String>();
		Iterator<Element> listIterator = element.elementIterator("list");
		while(listIterator.hasNext()) {
			Iterator<Element> valueIterator = listIterator.next().elementIterator("value");
			while(valueIterator.hasNext()) {
				String id = valueIterator.next().getTextTrim();
				if(!StringUtil.isEmpty(id)) {
					elements.add(id);
				}
			}
		}
		return elements;
	}
	
}
